//
//  UpdatePwdItemCell.swift
//  d11
//
//  Created by peale on 2018/10/1.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
typealias FieldChangeBlock = (_ text: String,_ row:Int) -> Void
typealias ShowPwdBlock = (_ row: Int) -> Void
class UpdatePwdItemCell: UITableViewCell {
    var fieldChangeBlock: FieldChangeBlock?
    func callChangeBlock(_ block: @escaping FieldChangeBlock) {
        
        fieldChangeBlock = block
    }
    var showPwdBlock: ShowPwdBlock?
    func callShowPwdBlock(_ block: @escaping ShowPwdBlock) {
        
        showPwdBlock = block
    }
    var bgImgView = UIImageView.init()
    var pwdField : UITextField?
    var iconImgView :UIImageView?
    var showPwdBtn : UIButton?
    var row : Int = 0
    var iamgeCode = UIImageView()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setUpUI() -> Void {
        self.backgroundColor  = UIColor.clear
        self.selectionStyle = UITableViewCell.SelectionStyle.none
      
        self.bgImgView.isUserInteractionEnabled = true
        iamgeCode.isHidden = true
        iamgeCode.isUserInteractionEnabled = true
      
       
        let tapgester = UITapGestureRecognizer(target: self, action: #selector(updateVerificationCode))
        iamgeCode.addGestureRecognizer(tapgester)
     //   self.bgImgView?.image = imageNamed("icon_my_cell_item")
        self.contentView.addSubview(bgImgView);
        self.bgImgView.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-10)
            make.height.equalToSuperview()
            make.centerX.equalTo(self.contentView)
        }
        let viewLine = UIView()
        viewLine.backgroundColor = UIColor.lightGray
        self.contentView.addSubview(viewLine);
        viewLine.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(1)
            make.top.equalTo(self.bgImgView.snp.bottom).offset(-5)
        }
      
        //32  38  16x   19
        self.pwdField = UITextField.init()
        self.pwdField?.textColor =  HexRGBAlpha(0x8E8F90, 1)
        self.pwdField?.font = UIFont.systemFont(ofSize: 15)
        self.pwdField?.textAlignment = NSTextAlignment.left
        self.pwdField?.keyboardType  = .asciiCapable
        self.pwdField?.placeholder = "请输入密码"
         self.pwdField?.leftViewMode = .always
        self.pwdField?.rightViewMode = .always
         self.pwdField?.isSecureTextEntry = true
        let leftView:UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 46, height: 51))
        self.iconImgView = UIImageView.init(image: UIImage.init(named: "show_password"))
        self.iconImgView?.frame = CGRect(x: 10, y: 15, width: 16, height: 19)
        leftView.addSubview(self.iconImgView!)
        self.pwdField?.leftView = leftView
        
        let rightView:UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 46, height: 51))
            rightView.isUserInteractionEnabled = true
        self.showPwdBtn = UIButton.init(type: UIButton.ButtonType.custom)
        self.showPwdBtn?.setImage(UIImage.init(named: "hide_password"), for: .normal)
        self.showPwdBtn?.frame = CGRect(x: 0, y: 0, width: 46, height: 51)
        self.showPwdBtn?.frame = CGRect(x: 10, y: 15, width: 16, height: 16)
        self.showPwdBtn?.addTarget(self, action: #selector(self.actionToShow(_:)), for: .touchUpInside)
      //  rightView.addSubview(showPwdBtn!)
        self.pwdField?.rightView = showPwdBtn
        self.bgImgView.addSubview(self.pwdField!)
        
        self.pwdField?.addTarget(self, action: #selector(self.actionToChanged(_:)), for: UIControl.Event.editingChanged)
        self.pwdField?.snp.makeConstraints{(make) in
            make.width.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalToSuperview().offset(-10)
        }
        self.contentView.addSubview(iamgeCode);
        iamgeCode.snp.makeConstraints { (make) in
            make.right.equalTo(-10)
            make.width.equalTo(60)
            make.height.equalTo(30)
            make.centerY.equalToSuperview()
        }
        self.updateVerificationCode()
    }
    
    func setData(placeholder:String,pwd:String,iconName:String,isShow:Bool,row:Int) -> Void {
        self.row = row
        self.pwdField?.placeholder = placeholder
        self.pwdField?.text = pwd
        self.iconImgView?.image = UIImage.init(named: iconName as String)
        if  isShow {
            self.showPwdBtn?.setImage(UIImage.init(named: "show_password"), for: .normal)
            self.pwdField?.isSecureTextEntry = !isShow
        }else{
            self.showPwdBtn?.setImage(UIImage.init(named: "hide_password"), for: .normal)
            self.pwdField?.isSecureTextEntry = !isShow
        }
        if row == 3 {
            iamgeCode.isHidden = false
            self.pwdField?.isSecureTextEntry = false
        }
     
    }
    @objc func actionToShow(_ sender: UIButton) -> Void {
        if showPwdBlock != nil {
            showPwdBlock!(self.row)
        }
    }
    @objc func actionToChanged(_ sender: UITextField) -> Void {
        if fieldChangeBlock != nil {
            fieldChangeBlock!(sender.text!,self.row)
        }
    }
    @objc func updateVerificationCode(){
        RequestHelper.get(atPath: "/service/verifycode", withCompletion: { data in
            let imageData:NSData = NSData(data: data)
           
            // When from background thread, UI needs to be updated on main_queue
            DispatchQueue.main.async {
                self.iamgeCode.image = UIImage(data: imageData as Data)
            }
        }, withError: { error in
//            DispatchQueue.main.async {
//                MBProgressHUD.showMessage("刷新验证码失败", to: self.bgView)
//            }
        })
    }
    
    @objc func updateVerificationCode2(){
           NetWorkRequest(API.verifycode(url: "833656a"), completion: {(responseData,statusCode,strData) -> (Void) in
               DispatchQueue.main.async {
                    let dict =  responseData["data"].dictionaryValue
                    let imageStr =  dict["image"]?.stringValue
                  
                   let imageData = Data(base64Encoded: imageStr ?? "")
                   self.iamgeCode.image = UIImage(data: imageData ?? Data())
               }
              
               
           }, failed: { (faildInfo,reCode,msg) -> (Void) in
//               DispatchQueue.main.async {
//                UIHelper.alertSimpleMessage(about: faildInfo, withDescription: "", withOKButton: <#T##Bool#>)
//                    MBProgressHUD.showMessage(faildInfo, to: self.bgView)
//               }
           }) { () -> (Void) in
//               DispatchQueue.main.async {
//                   MBProgressHUD.showMessage("刷新验证码失败。", to: self.bgView)
//               }
           }
       }
}
